﻿using System;
using cz.uhul.DSMLv2;


namespace cz.uhul.DSMLv2.Server.Sql
{




  public static partial class LdRequestServerExtension
  {






    public static LdModifyDnResponse Execute(this LdModifyDnRequest modDnReq)
    {

      LdDistinguishedName dn;
      LdDistinguishedName newdn;

      if (string.IsNullOrEmpty(modDnReq.NewRDN))
        return new LdModifyDnResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "modifyDNRequest failed"
          , "invalid DN:[empty]"
        );

      string strNewDn;

      if(string.IsNullOrEmpty(modDnReq.NewSuperior))
        strNewDn = modDnReq.NewRDN;

      else
        strNewDn = modDnReq.NewRDN + "," + modDnReq.NewSuperior;

      if (!LdDistinguishedName.TryParse(modDnReq.DistinguishedName, out dn))
        return new LdModifyDnResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "modifyDNRequest failed"
          , "invalid DistinguishedName:" + modDnReq.DistinguishedName
        );

      if (!LdDistinguishedName.TryParse(strNewDn, out newdn))
        return new LdModifyDnResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "modifyDNRequest failed"
          , "invalid new DistinguishedName:" + strNewDn
        );

      try
      {
        LdDatabase.ModifyDn(modDnReq.DistinguishedName, newdn, newdn.RDNValue, modDnReq.NewSuperior, modDnReq.DeleteOldRDN);

        return new LdModifyDnResponse(LdResultCodeEnum.Success, null, null);

      }
      catch (Exception e)
      {
        //rollback tran??
        return new LdModifyDnResponse(LdResultCodeEnum.OperationsError, "modifyDNRequest failed for dn=" + modDnReq.DistinguishedName, e.Message);
      }

    }



  }

}